#!/bin/bash
set -e
export ORACLE_HOME=/data/u01/app/oracle/app/oracle/product/11.2.0/db
export ORACLE_SID=interlib
export PATH=$ORACLE_HOME/bin:$PATH

# 日志
LOGFILE="/data/backup/rman_backup_$(date +%F).log"
exec >> $LOGFILE 2>&1

# 清理30天前的备份，可以不设置，“DELETE NOPROMPT OBSOLETE;” 会自动清理过期物理文件。
#find /data/backup/ -type f -mtime +30 -exec rm -f {} \;

# 备份日期变量
BKDATE=$(date +%F)

#整库备份操作
#BACKUP INCREMENTAL LEVEL 1 DATABASE FORMAT '/data/backup/db_inc1_$(date +%F)_%U.bak';
#改成下列语句
#BACKUP DATABASE FORMAT '/data/backup/db_full_${BKDATE}_%U.bak';



# 全库备份
rman target / <<EOF
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 7 DAYS;
DELETE NOPROMPT OBSOLETE;
DELETE NOPROMPT EXPIRED ARCHIVELOG ALL;
BACKUP DATABASE FORMAT '/data/backup/db_full_${BKDATE}_%U.bak';
BACKUP ARCHIVELOG ALL FORMAT '/data/backup/arch_$(date +%F)_%U.bak';
BACKUP CURRENT CONTROLFILE FORMAT '/data/backup/ctl_$(date +%F)_%U.bak';
EXIT
EOF


# 传输当天备份、归档日志、控制文件到备库
#inc_files=$(find /data/backup/ -maxdepth 1 -type f -name "db_inc1_${BKDATE}_*.bak" -mtime 0)
inc_files=$(find /data/backup/ -maxdepth 1 -type f -name "db_full_${BKDATE}_*.bak" -mtime 0)
arch_files=$(find /data/backup/ -maxdepth 1 -type f -name "arch_${BKDATE}_*.bak" -mtime 0)
ctl_files=$(find /data/backup/ -maxdepth 1 -type f -name "ctl_${BKDATE}_*.bak" -mtime 0)

if [ -n "$inc_files" ]; then
  echo "[$(date '+%F %T')] 正在传输备份文件到备库..."
  echo "$inc_files" | xargs -I {} scp {} oracle@10.10.10.2:/data/backup/
  echo "备份完成，备份文件已传输到备库。"
else
  echo "[$(date '+%F %T')] 没有当天备份文件需要传输。"
fi

if [ -n "$arch_files" ]; then
  echo "[$(date '+%F %T')] 正在传输归档日志文件到备库..."
  echo "$arch_files" | xargs -I {} scp {} oracle@10.10.10.2:/data/backup/
  echo "备份完成，归档日志文件已传输到备库。"
else
  echo "[$(date '+%F %T')] 没有当天归档日志文件需要传输。"
fi


if [ -n "$ctl_files" ]; then
  echo "[$(date '+%F %T')] 正在传输控制文件备份到备库..."
  echo "$ctl_files" | xargs -I {} scp {} oracle@10.10.10.2:/data/backup/
  echo "备份完成，控制文件备份已传输到备库。"
else
  echo "[$(date '+%F %T')] 没有当天控制文件备份需要传输。"
fi